import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {Image, Picker, Text, View} from '@tarojs/components'
import {AtIcon, AtActionSheet, AtActionSheetItem} from 'taro-ui'
import {http} from "../../utils/http";
import {INDEX_GOODS, MD_CREAT_ORDER, MD_SUPPLIERS, MD_CHECK_ORDER_STATUS} from "../../constants/api";
import Headerbar from "../components/header-bar/header-bar";
import {getHeadTop} from "../../utils/tools";
import {newHttp} from "../../utils/request";
import './money.scss'


interface LoginParamType {
  nickName: string
  gender: number
  language: string
  city: string
  province: string
  country: string
  avatarUrl: string
  bindSellerId: number
  itemUUID: string
  path: string
}

type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  searchBarTop: number
  limit: number
  list: any
  supplierList: any
  supplierIndex: number
  supplierName: string
  dowloadQrcode: boolean
  loginParam: any
  qrCoderUrl: string
  supplier_id: number
  orderNum: string
  status: string
}

export default class Money extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    searchBarTop: 0,
    limit: 10,
    list: [],
    supplierList: [],
    supplierIndex: 0,
    supplierName: '',
    dowloadQrcode: false,
    loginParam: {
      nickName: '',
      gender: 1,
      language: '',
      city: '',
      province: '',
      country: '',
      avatarUrl: '',
      bindSellerId: 0,
      itemUUID: '',
      path: '',
    },
    qrCoderUrl: '',
    supplier_id: 0,
    orderNum: '',
    status: '未支付',
  }

  async UNSAFE_componentWillMount() {
    const headTop: any = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 40)
    this.setState({searchBarTop})
    let {supplierName, supplier_id} = this.state
    const supplierIndex = Taro.getStorageSync('supplierIndex') || 0
    const supplierList = await newHttp.catchPost(MD_SUPPLIERS);
    if (supplierList && +supplierIndex <= supplierIndex.length) {
      supplierName = supplierList[supplierIndex].company
      supplier_id = supplierList[supplierIndex].id
      const qrCoderData = await newHttp.catchPost(MD_CREAT_ORDER, {supplier_id})
      this.checkOrderStatus()
      this.setState({
        qrCoderUrl: qrCoderData.wxVCodeImgStr,
        orderNum: qrCoderData.orderNum,
        supplierList,
        supplierIndex,
        supplierName,
        supplier_id
      })
    }
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }

  timer: any
  page = 1
  shareParams = ''
  loginmsg = null

  async getAdds(page = 1) {
    const {limit} = this.state
    const indexGoods = await http.post(INDEX_GOODS, {p: page, k: '', areaId: this.props.location.region_id, order: 0})
    if (indexGoods) {
      if (indexGoods.list.length < limit) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return indexGoods.list
    } else {
      return []
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.list
      this.page++
      const newData = await this.getAdds(this.page)
      this.setState({list: [...old, ...newData]})
    }
  }


  supplierChange(e) {
    const {supplierList} = this.state
    if (supplierList.legnth <= 0) {
      return false
    }
    const supplierIndex = Number(e.detail.value)
    this.setState({
      supplierIndex,
      supplierName: supplierList[supplierIndex].company,
      supplier_id: supplierList[supplierIndex].id
    }, async () => {
      Taro.setStorageSync('supplierIndex', supplierIndex)
      const qrCoderData = await newHttp.catchPost(MD_CREAT_ORDER, {supplier_id: this.state.supplier_id})
      this.setState({qrCoderUrl: qrCoderData.wxVCodeImgStr, orderNum: qrCoderData.orderNum})
    })
  }

  async refresh() {
    const {supplier_id} = this.state
    const qrCoderData = await newHttp.catchPost(MD_CREAT_ORDER, {supplier_id})
    if (qrCoderData) Taro.showToast({title: '刷新成功', icon: 'none'})
    this.setState({qrCoderUrl: qrCoderData.wxVCodeImgStr, orderNum: qrCoderData.orderNum})
  }

  checkOrderStatus() {
    this.timer = setInterval(async () => {
      const data = await newHttp.catchPost(MD_CHECK_ORDER_STATUS + this.state.orderNum)
      if (data.status == '支付失败') {
        this.refresh()
      }
      this.setState({status: data})
    }, 1500)
  }

  handleCancel() {
    this.setState({dowloadQrcode: false})
  }

  handleClose() {
    this.setState({dowloadQrcode: false})
  }

  jump() {
    this.setState({dowloadQrcode: false})
    Taro.navigateTo({url: '/distributor/poster/poster?url=' + this.state.qrCoderUrl})
  }

  jumpPage(url) {
    Taro.navigateTo({url})
  }

  onceJump() {
    Taro.navigateTo({url: '/other/buy-order/buyorder?orderNum=' + this.state.orderNum + '_' + this.state.supplierName + `_${this.state.supplier_id}_1787`})
  }

  render() {
    const {status, qrCoderUrl, supplierList, supplierIndex, supplierName, dowloadQrcode, searchBarTop} = this.state
    return (
      <View className='success-order-root'>
        <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <Headerbar title='小程序码收款' />
        </View>
        <View className='supplier-box f-c-c'>
          <View> 供应商: {supplierName} </View>
          <Picker onChange={this.supplierChange.bind(this)} range={supplierList} value={supplierIndex}
            rangeKey='company'
          >
            <View>
              <Text className='btn'>切换</Text>
            </View>
          </Picker>
        </View>
        <View className='content-box'>
          <View className='title-box f-c-b'>
            <View className='lt'>小程序码收款</View>
            <View onClick={() => {
              this.setState({dowloadQrcode: true})
            }} className='more-box f-c-c'
            >
              <View className='more' />
              <View className='more' />
              <View className='more' />
            </View>
          </View>
          <View className='qrcoder-box'>
            <View className='text-one'>扫码向我付钱</View>
            <View onClick={this.onceJump.bind(this)}>
              <Image className='qrcode'
                src={qrCoderUrl}
                mode='widthFix'
              />
            </View>
            <View onClick={this.refresh.bind(this)} className='text-two'>刷新</View>
          </View>
          <View onClick={this.jumpPage.bind(this, '/other/buy-order/recording')} className='ret-box f-c-b'>
            <View className='f-c-c'>
              <AtIcon className='shoukuanjilu' size='22px' prefixClass='car' value='iconshoukuanjilu'
                color='#EC9F4F'
              />
              <View>买单记录</View>
            </View>
            <View>
              <AtIcon prefixClass='car' value='iconright' size='12px' color='#B1B1B1' />
            </View>
          </View>
          <View className='AtDivider' />
          {status && status.nick_name && status.photo && <View className='pay-ret-box f-c-b'>
            <View className='f-c-c'>
              <View className='head'> <Image className='head-img' src={status.photo} mode='widthFix' /> </View>
              <View className='nickname'>{status.nick_name}</View>
            </View>
            <View>
              {status.status !== '支付成功' && <View className='pay-err'>{status.status}</View>}
              {status.status == '支付成功' && <View className='f-c-c'>
                <View className='moeny-icon'>¥</View>
                <View className='price'>{status.total_fee}</View>
              </View>}
            </View>
          </View>}
        </View>
        <AtActionSheet cancelText='取消' isOpened={dowloadQrcode} onCancel={this.handleCancel.bind(this)}
          onClose={this.handleClose.bind(this)}
        >
          <AtActionSheetItem onClick={this.jump.bind(this)}>
            下载二维码
          </AtActionSheetItem>
        </AtActionSheet>
      </View>
    )
  }
}

